//
//  GroupGoodsDetailCtr.swift
//  eemall
//
//  Created by zhuxietong on 2018/12/24.
//  Copyright © 2018 tianrun. All rights reserved.
//
import UIKit
import soapp
import Eelay
import AsyncDisplayKit

open class GroupGoodsDetailCtr: GoodsDetailCtr {
    override open var sections: TP.section{
        get{
            let groups = DataNode.path(node: "goodsteams.teams", mo.detail, value: NSMutableArray())
            var showGrop = "NO"
            if groups.count > 0
            {
                showGrop = "YES"
            }
            
            let sec:TP.section = [
                [
                    ["cellID":"info","__model":mo.detail],
                    ["cellID":"groupTitle","__model":mo.detail,"title":"火热拼团中".loc,"__show":showGrop]
                ],
                [
                    //                    ["cellID":"group"],
                    //                    ["cellID":"group"],
                ],
                [
                    ["cellID":"server","__model":mo.detail],
                ],
                section3 as! Array<[String : Any]>,
                [
                    ["cellID":"__blank"],
                    ["cellID":"recGoods",
                     "list":[
                        //                            ["img":__images.one_str,"title":__titles.one_str],
                        //                            ["img":__images.one_str,"title":__titles.one_str],
                        //                            ["img":__images.one_str,"title":__titles.one_str],
                        ]
                    ],
                ]
            ]
            return sec
        }
    }
    
    open override var detailURL:String{
        get{
            return _SURL.团购商品详情.url
        }
    }
    override open var selector: TP.selector{
        get{
            let sel:TP.selector = [
                "cellID<info>":TopInfoCell.self,
                "cellID<groupTitle>":TitleCell.self,
                "cellID<server>":ServerCell.self,
                "cellID<web>":GoodsWebNode.self,
                "cellID<comment>":CommentCell.self,
                "cellID<emptyComment>":EmptyCommentCell.self,
                "cellID<moreComment>":MoreCommentCell.self,
                "cellID<recGoods>":RecItemCell.self,
                "cellID<__blank>":WhiteCell.self,
                "tagName<img>":ImageCell.self,
                "<section2>":TextNodeCell.self,
                "<section1>":GroupCell.self,
            ]
            return sel
        }
    }
    
    open override func viewDidLoad() {
        bar = IweGoodsDetailCtr.IweSegbar()
        
        self.scheme = .group
        bottomBar = GroupBuyBar()
        super.viewDidLoad()
    }
    
    
    override open func mo_detail_reload() {
        mo.model["__scheme"] = self.scheme.rawValue
        GroupGoodsDetailCtr.preDealDetail(detail: mo.detail, groupid: nil)
        super.mo_detail_reload()
    }
    
    open override func willReloadData() {
        
        let groups = DataNode.path(node: "goodsteams.teams", mo.detail, value: NSMutableArray())
        self.tableNode.model["section1"] = groups
        startTimer()
    }
    
    var inRefreshGroup = false
    
    
    
    var timer:SwiftTimer? = nil
    
    
    
    //继承商品详情页为简化界面数据显示，对订单详情进行预处理
    static func preDealDetail(detail:NSMutableDictionary,groupid:String?) {
        var gid = groupid
        if let _gid = groupid
        {
            if _gid == "0" || _gid == ""
            {
                gid = nil
            }
        }
        
        if detail["is_ladder",false.tag] == true.tag{
            let groups = DataNode.path(node: "ladder", detail, value: NSMutableArray())
            var minPrice = detail["ladder.0.ladder_price","0"]
            groups.list { (obj:NSMutableDictionary, i) in
                let price = obj["ladder_price","0"]
                if let agid = gid{
                    if obj["id",""] == agid
                    {
                        minPrice = price
                    }
                }
                else{
                    if minPrice > price{
                        minPrice = price
                    }
                }
            }
            detail["__groupsprice"] = minPrice
        }
        else{
            detail["__groupsprice"] = detail["groupsprice",""]
        }
    }
    
    
    open override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        super.touch(cell: cell, actionID: actionID, model: model)
        if actionID == "join"
        {
            let bar = bottomBar as? GroupBuyBar
            let obj = bottomBar.mo.model.mutable_dictionary
            GroupGoodsDetailCtr.preDealDetail(detail: obj, groupid: model["ladder_id",""])
            bottomBar.mo.model = obj
            let  price = bottomBar.mo.model[float:"__groupsprice",0]
            bar?.joinGroup(groupID: model["ladder_id",""], teamID: model["teamid",""], price: price,invitationCode: nil)
        }
    }
    
    open override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 3{
            return 56
        }
        return  0
    }
    
    
    deinit {
        stopTimer()
    }
}


extension GroupGoodsDetailCtr{
    
    class GroupCell: JoCellNode {
        let headV = JoImageNode()
        let nameL = ASTextNode2()
        let timeL = ASTextNode2()
        let numL = ASTextNode2()
        let actionBt = ASButtonNode()
        
        let timeNode = GroupInfoCtr.EndTimerNode1()
        
        let statusL = ASTextNode2()
        
        var groupStatus:GroupPurchaseStatus = .process
        
        var addAnimationV = ASButtonNode()
        
        
        override func addLayoutRules() {
            weak var wself = self
            headV.view.bsui.set(radius: 21, width: 1, color: UIColor(shex: "#eee8"))
            headV.ui.holder(type: .head).set(radius: 21, width: 1, color: UIColor(shex: "#eee8"))
            timeNode.observerStatus = {
                isTimeOut in
                if isTimeOut{
                    "拼团结束".loc.alert()
                    wself?.active(ID: "timeout")
                }
            }
            addAnimationV.ui.font(size: 9).padding(insets: [3,3]).buttonColor(hex: AppTheme.main_hex).ncolor(hex: "#fff").ntitle(title: "+1")
        }
        
        override func mo_model_reload() {
            
            headV.img_url = mo.model["avatar",""]
            nameL.attributedText = __names.one_str.ui.font12.color(color: ._foregroundWeak).astring
            let num = mo.model[int:"num",1]
            let total = mo.model[int:"groupnum",1]
            
            numL.attributedText = "\(num)/\(total)人".ui.font12.color(color: ._foregroundWeak).astring
            timeL.attributedText = "剩余时间".loc.ui.font12.color(color: ._foreground).astring
            
            actionBt.ui.font(size: 11).ncolor(hex: "#fff").padding(insets: [6,12]).ntitle(title: "去拼单".loc).buttonColor(hex: AppTheme.main_hex).set(radius: 3, width: nil, color: nil)
            actionBt.addTarget(self, action: #selector(joinAction), forControlEvents: .touchUpInside)
            
            let end = stampToTime(mo.model["endtime",""])
            timeNode.endTime = end
            timeNode.mo.model = mo.model
            checkStatus(isTimeOut: timeNode.isTimeout)
            
            weak var wself = self
            self.addAnimationV.view.alpha = 0
            
            co_delay(delay: 0.1) {
                wself?.noticeShow()
            }
            
            //            separatorColor = UIColor(shex: "#ccc")
            //            separatorHeight = TP.separatorHeight
            //            separatorInset = [0,20,0,20]
            
        }
        
        
        func noticeShow() {
            if mo.model["__change",""] == "0"{
                return
            }
            if mo.model["__change",""] == ""{
                return
            }
            
            let anView:UIView? = self.addAnimationV.view
            self.addAnimationV.view.layer.transform = CATransform3DMakeScale(0.4, 0.4, 0.0);
            anView?.alpha = 0
            UIView.animate(withDuration: 0.15, animations: { () -> Void in
                anView?.alpha = 1
                anView?.layer.transform = CATransform3DMakeScale(1.2, 1.2, 0.0);
            }, completion: { (finish) -> Void in
                anView?.alpha = 1
                UIView.animate(withDuration: 0.3, animations: { () -> Void in
                    anView?.layer.transform = CATransform3DMakeScale(1, 1, 0.0);
                }, completion: { (finish) -> Void in
                    if finish{
                        UIView.animate(withDuration: 0.4, delay: 1.2, options: [], animations: {
                            anView?.alpha = 0
                        }, completion: { (finish) in
                            anView?.alpha = 0
                        })
                    }
                })
            })
            //            weak var ws = self
            //            co_delay(delay: 2) {
            //                ws?.noticeHidden()
            //            }
        }
        
        func noticeHidden() {
            let anView:UIView? = self.addAnimationV.view
            UIView.animate(withDuration: 0.3,animations: {
                anView?.alpha = 0
                anView?.layer.transform = CATransform3DMakeScale(0.7, 0.7, 0.0);
                
            }, completion: { (Bool) -> Void in
                
            })
            
        }
        
        
        func checkStatus(isTimeOut:Bool) {
            switch groupStatus {
            case .failed:
                statusL.attributedText = "拼团失败".loc.ui.bfont12.color(hex: AppTheme.main_hex).astring
            case .process:
                statusL.attributedText = "拼团中".loc.ui.bfont12.color(hex: AppTheme.main_hex).astring
            case .success:
                statusL.attributedText = "拼团成功".loc.ui.bfont12.color(hex: AppTheme.main_hex).astring
            }
        }
        
        @objc func joinAction(){
            weak var wself = self
            //            let md = mo.model["mid",""]
            let obj = mo.model
            //            print("+++++iiiiii",mo.model);
            JoUser.authAction(message: "请先登录后进行相关操作".loc, at: mo.controller) { (u) in
                GroupActive.seeGroup(obj: obj, at: wself?.mo.controller)
                //                wself?.active(ID: "join")
            }
        }
        
        override func specGetter() -> _Spec {
            let spec = _Spec.stack(["h|10",&-.center,[8,AppTheme.edge]], childs: [
                headV["42",42],
                .stack(["v|5",&-.stretch,_grow(1),_shrink(1),_justfy(.space_between)], childs: [
                    .stack(["h|10",&-.center], childs: [
                        statusL.Spec,
                        numL.Spec,
                        addAnimationV.Spec
                    ]),
                    .stack(["h|10",&-.center], childs: [
                        timeL[[3,0,0,0]],
                        timeNode.Spec
                    ]),
                ]),
                actionBt[[15,0,0,0]]
            ])
            return spec
        }
        
    }
    
    class TitleCell: JoCellNode {
        let titleL = JoTextNode()
        let moreBt = ASButtonNode()
        override func mo_model_reload() {
            
            
            //            separatorHeight = TP.separatorHeight
            //            separatorColor = UIColor.table_bg_color
            backgroundColor = .clear
            moreBt.ui.font(size: 13).ncolor(color: ._foregroundWeak).ntitle(title: mo.model["tag","更多".loc])
            titleL.attributedText = mo.model["title",""].ui.font12.color(color: ._foregroundWeak).astring
            moreBt.addTarget(self, action: #selector(showMore), forControlEvents: .touchUpInside)
            
            if show{
                separatorTopHeight = TP.separatorHeight
                separatorTopColor = ._separator
            }
            else{
                separatorTopColor = .clear
                separatorTopHeight = 0
            }
        }
        
        @objc func showMore() {
            
            let ctr = GroupListCtr()
            ctr.mo.model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            mo.controller?.navigationController?.pushViewController(ctr, animated: true)
        }
        
        var show:Bool{
            get{
                return mo.model["__show","NO"] == "YES"
            }
        }
        let blank = ASDisplayNode()
        override func specGetter() -> _Spec {
            
            if show
            {
                return _Spec.stack(["h|16",[10,AppTheme.edge],_nowrap,&-.center], childs: [
                    titleL[_shrink(1),_grow(1)],
                    moreBt.Spec
                ])
            }
            return _Spec.wrapper(blank.Spec)
        }
    }
    
    
    
    
}


extension GroupGoodsDetailCtr{
    open class GroupBuyBar: BuyBar {
        
        public let singleTitleL = UILabel()
        
        public let groupTitleL = UILabel()
        
        public let singleBuyBt = UIButton()
        
        public var buyWidthC = NSLayoutConstraint()
        
        open override func didLayoutRules() {
            sellerBt.bt.setImage( UIImage(named: "shop_store_gray"), for: .normal)
            sellerBt.bt.addTarget(self, action: #selector(seeSeller), for: .touchUpInside)
            careBt.bt.setImage(UIImage(named: "goods_save_n"), for: .normal)
            careBt.bt.setImage( UIImage(named:"goods_save_s"), for: .selected)
            careBt.bt.addTarget(self, action: #selector(careToggle), for: .touchUpInside)
            
            sellerBt.lable.ui.cl_888.font10.center.text("店铺".loc)
            careBt.lable.ui.cl_888.font10.center.text("收藏".loc)
            buyBt.addTarget(self, action: #selector(createGroupAction), for: .touchUpInside)
            singleBuyBt.addTarget(self, action: #selector(singleBuy), for: .touchUpInside)
            
            
            singleBuyBt.setBackgroundImage(UIImage.gradient(colors: ThemeSet.Gradient.groupSingle, size: [49,100]), for: .normal)
            
            line.backgroundColor = .clear
            
        }
        
        @objc open func singleBuy(){
            specSelectorTask = .groupSingleBuy
            self.buySelector.bar.nextBar.nextActions = [.团购单买]
            buyAction()
        }
        
        
        
        public var groupId:String? = nil
        public var teamid:String? = nil
        
        
        
        @objc open func createGroupAction(){
            weak var wself = self
            GroupCreater.create(goods: mo.model, at: mo.controller, confirm: { obj in
                wself?.buySelector.bar.nextBar.nextActions = [.发起团购]
                if let info = obj{
                    wself?.groupId = info["id",""]
                    wself?.buySelector.mo.detail["__groupsprice"] = info["ladder_price",""]//规格选择页面价格显示相关
                    wself?.specSelectorTask = .group(info: [String:Any]())
                    wself?.buyAction()
                }
                else{
                    wself?.groupId = nil
                    wself?.specSelectorTask = .group(info: [String:Any]())
                    wself?.buyAction()
                }
            })
        }
        
        open func joinGroup(groupID:String?,teamID:String,price:CGFloat,invitationCode:String?) {
            var gid = groupID
            if let _gid = groupID
            {
                if _gid == "0" || _gid == ""
                {
                    gid = nil
                }
            }
            self.teamid = teamID
            self.buySelector.bar.nextBar.nextActions = [.参与拼团]
            self.groupId = gid
            self.buySelector.mo.detail["__groupsprice"] = price//规格选择页面价格显示相关
            self.specSelectorTask = .group(info: [String:Any]())
            self.buyAction()
        }
        
        
        open override func optionConfirm(values: [String : Any], next: SpecSelectorNext) {
            var vs = values
            if let gID = groupId{
                vs["group_id"] = gID
            }
            
            
            switch next {
            case .发起团购:
                co_delay(delay: 0.26) {[weak self] in
                    let ctr = GroupOrderConfirmCtr()
                    ctr.groupType = .start(info:vs)
                    self?.mo.controller?.navigationController?.pushViewController(ctr, animated: true)
                }
                
            case .团购单买:
                co_delay(delay: 0.26) {[weak self] in
                    let ctr = GroupOrderConfirmCtr()
                    ctr.groupType = .single(option: vs)
                    self?.mo.controller?.navigationController?.pushViewController(ctr, animated: true)
                }
                
            case .参与拼团:
                if let tID = teamid
                {
                    vs["teamid"] = tID
                }
                co_delay(delay: 0.26) {[weak self] in
                    let ctr = GroupOrderConfirmCtr()
                    ctr.groupType = .join(info: vs)
                    self?.mo.controller?.navigationController?.pushViewController(ctr, animated: true)
                }
                
                break
            default:
                break
            }
            
        }
        
        open override func addLayoutRules() {
            let line = UIView()
            let line2 = UIView()
            contentView.eelay = [
                [sellerBt,[ee.L.Y,[10,0]],"40",40],
                [careBt,[sellerBt,ee.R,ee.L,10],[ee.Y],"40",40],
                [buyBt,[ee.T.R.B,[6,-AppTheme.edge,-6]]],
                [singleBuyBt,[buyBt,ee.L,ee.R,-ThemeSet.buttonSpace],[ee.T.B,[6,-6]],110.co],
                [line,[ee.T.L.R],"\(TP.separatorHeight)"],
                //                [line2,[ee.L.B.R],"\(TP.separatorHeight)"]
            ]
            
            buyWidthC = NSLayoutConstraint(item: buyBt, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 200.co)
            buyBt.addConstraint(buyWidthC)
            buyBt.eelay = [
                [groupTitleL,[ee.X.Y]],
            ]
            singleBuyBt.eelay = [
                [singleTitleL,[ee.X.Y]],
            ]
            
            _ = buyBt.ui.font(size: 12).ncolor(hex: "#fff").ntitle(title: "").padding(insets: [8,16])
            //            buyBt.setBackgroundImage(UIImage(named: "shop_buy"), for: .normal)
            _ = singleBuyBt.ui.font(size: 11).ncolor(hex: "#fff").ntitle(title: "").buttonColor(color: ___shop.tint)
            
            line2.backgroundColor = UIColor._separator
            line.backgroundColor = ._separator
            
            singleBuyBt.setBackgroundImage(UIImage.gradient(colors: ThemeSet.Gradient.groupSingle, size: [49,110.co]), for: .normal)
            buyBt.setBackgroundImage(UIImage.gradient(colors: ThemeSet.Gradient.groupBuy, size: [49,110.co]), for: .normal)
            
            buyBt.bsui.set(radius: ThemeSet.buttonRadius, width: nil, color: nil)
            
            singleBuyBt.bsui.set(radius: ThemeSet.buttonRadius, width: nil, color: nil)
            
            
            
            groupTitleL.numberOfLines = 2
            groupTitleL.attributedText = "¥ 1209.00\n".ui.center.bfont13.cl_fff.lineSpace(1).astring + "发起拼团".loc.ui.font11.center.cl_fff.lineSpace(1).astring
            
            singleTitleL.numberOfLines = 2
            singleTitleL.attributedText = "¥ 209.00\n".ui.center.bfont13.cl_fff.lineSpace(1).astring + "单独购买".loc.ui.font11.center.cl_fff.lineSpace(1).astring
        }
        
        
        override open func mo_model_reload() {
            
            let groupsPrice = mo.model[float:"__groupsprice",0]
            
            if mo.model["is_ladder",false.tag] == true.tag{
                let priceTag = "[XX]¥ 起".replaceVars(values: groupsPrice.price_display)
                groupTitleL.attributedText = "\(priceTag)\n".ui.center.bfont13.cl_fff.lineSpace(1).astring + "发起拼团".loc.ui.font11.center.cl_fff.lineSpace(1).astring
            }
            else{
                let priceTag = "[XX] ¥".replaceVars(values: groupsPrice.price_display)
                groupTitleL.attributedText = "\(priceTag)\n".ui.center.bfont13.cl_fff.lineSpace(1).astring + "发起拼团".loc.ui.font11.center.cl_fff.lineSpace(1).astring
            }
            
            let singlePrice = mo.model[float:"singleprice",0]
            let priceTag = "[XX] ¥".replaceVars(values: singlePrice.price_display)
            
            singleTitleL.attributedText = "\(priceTag)\n".ui.center.bfont13.cl_fff.lineSpace(1).astring + "单独购买".loc.ui.font11.center.cl_fff.lineSpace(1).astring
            
            if mo.model["single",true.tag] == false.tag
            {
                buyWidthC.constant = 200.co
                singleBuyBt.alpha = 0
            }
            else{
                buyWidthC.constant = 110.co
                singleBuyBt.alpha = 1
            }
            //            print("DD++++++IIII|\(mo.model)")
        }
        
    }
    
    
    class TopInfoCell: InfoCell {
        
        override func mo_model_reload() {
            super.mo_model_reload()
            separatorColor = .clear
            
            nameL.textNode.maximumNumberOfLines = 3
            backgroundColor = .clear
            tagBt.backgroundColor = .clear
            let model = DataNode.path(node: "__model", mo.model, value: NSMutableDictionary())
            
            nameL.attributedText =  model.possible("subtitle","title", default: "").ui.font12.color(color: ._foreground).lineSpace(7).astring
            
            let price = model[float:"__groupsprice",0]
            let old_price = model[float:"price",0]
            var priceStr = "\("拼团价".loc)   ".ui.bfont14.color(color: ._weak).astring + "¥ ".ui.bfont12.color(color: ___shop.tint).astring + price.price_display.ui.color(color: ._tint).bfont17.astring
            
            if model["is_ladder",false.tag] == true.tag{
                //                priceStr = priceStr + " 起     ".ui.font12.cl_999.astring
                priceStr = priceStr + "     ".ui.font12.color(color: ._weak).astring
                
            }
            else{
                priceStr = priceStr + "     ".ui.font12.color(color: ._weak).astring
            }
            
            
            if price < old_price
            {
                let old_priceStr = ("\("¥".loc) " +  old_price.price_display).ui.color(hex: "#aaa").font12.append(.strikethroughStyle, 1).append(.strokeColor, UIColor(shex:"#aaa")).astring
                priceL.attributedText = (priceStr + old_priceStr)
            }
            else{
                priceL.attributedText = priceStr
            }
        }
        
        
        override func specGetter() -> _Spec {
            //            let overTag:_Spec = .over([], over: .stack([[-2,0,0,0]], childs: [
            //                tagBt.Spec
            //                ]), back: nameL.Spec)
            
            let w = (Swidth - 2.0 * AppTheme.edge)/3.0
            let bt_spec:_Spec = .stack(["h",&-.center,_justfy(.space_between),_nowrap,(Swidth-2*AppTheme.edge)], childs: [
                postL[w,_grow(1)],
                numL[w,_grow(1)],
                locationL[w,_grow(1)]
            ])
            let sep:_Spec = .stack([[16,AppTheme.edge],"v|10",_justfy(.space_between)], childs: [
                priceL.Spec,
                nameL.Spec,
                bt_spec
            ])
            return sep
        }
    }
}
